import CryptoJS from 'crypto-js'
import {sharedKey,generateKeyPair} from "curve25519-js"
/**
 * 加密
 */

// 生成公私钥
export const getKeyPair = (uid) => {
  const hex = uuid2(64, 16);//生成UUid
  const key = generateKeyPair(toUint8Array(hex)); //generateKeyPair需传入为Uint8Array类型的方法
  const keyPair = {
    private: toBuffer(key.private).toUpperCase(),
    public: toBuffer(key.public).toUpperCase()
  }
  //把key存储起来（db或本地缓存）
  return keyPair
}
//生成共享秘钥
export const getSharedKey = (publicKey, privateKey) => {
  return toBuffer(sharedKey(toUint8Array(privateKey), toUint8Array(publicKey))).substring(0, 16).toUpperCase()
}

//生成UUid len 长度 radix 进制
export const uuid2 = (len, radix) => {
  var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/=".split("")
  var uuid = [],
    i
  radix = radix || chars.length
  if (len) {
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
  } else {
    var r;
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
    uuid[14] = "4";
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16);
        uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
      }
    }
  }
  return uuid.join("");
}

//转换为ArrayBuffer类型
function toBuffer(res) {
  return Buffer.from(res).toString("hex")
}


//转换为Uint8Array类型
function toUint8Array(res) {
  return Uint8Array.from(Buffer.from(res, "hex"));
}

CryptoJS.enc.u8array = {
  stringify: (wordArray) => {
    // Shortcuts
    var words = wordArray.words;
    var sigBytes = wordArray.sigBytes;
    // Convert
    var u8 = new Uint8Array(sigBytes);
    for (var i = 0; i < sigBytes; i++) {
      var byte = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
      u8[i] = byte;
    }
    return u8;
  },
  parse: (u8arr) => {
    // Shortcut
    var len = u8arr.length;
    // Convert
    var words = [];
    for (var i = 0; i < len; i++) {
      words[i >>> 2] |= (u8arr[i] & 0xff) << (24 - (i % 4) * 8);
    }
    return CryptoJS.lib.WordArray.create(words, len);
  }
}

// 加密方法 传入明文的uint8数组
export const getAesString = (array, shareKey) => {
  // console.log(shareKey)
  var key = CryptoJS.enc.Latin1.parse(shareKey)
  var acontent = array
  // 将明文转换成WordArray
  var contentWA = CryptoJS.enc.u8array.parse(acontent)
  // 插件要求明文是base64格式
  // var dcBase64String = contentWA.toString(CryptoJS.enc.Base64)
  // 加密 选定mode是CFB类型，无偏移量
  var encrypted = CryptoJS.AES.encrypt(contentWA, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  // 将密文转回uint8数组
  var bv = CryptoJS.enc.u8array.stringify(encrypted.ciphertext)
  // console.log(bv)
  return bv
}

export const getDAesString = (array, shareKey) => {
  // console.log(array)
  // console.log(shareKey)

  var key = CryptoJS.enc.Latin1.parse(shareKey)
  var acontent = array
  // 将密文转换成WordArray
  var contentWA = CryptoJS.enc.u8array.parse(acontent)
  // 插件要求密文是base64格式
  var dcBase64String = contentWA.toString(CryptoJS.enc.Base64)
  // 解密 选定mode是CFB类型，无偏移量
  var decrypted = CryptoJS.AES.decrypt(dcBase64String, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  // 将解密后的明文转回uint8数组
  var bv = CryptoJS.enc.u8array.stringify(decrypted)
  return bv
}